using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;
using System.Xml;

namespace TelephoneDirectory
{
    class Add
    {
        public string _Name, _Code, _Address, _PhoneNumber;

        public Add()
        {
            Console.WriteLine("\n Moi nhap ten : "); _Name = Console.ReadLine();
            Console.WriteLine("\n Moi nhap ma vung : "); _Code = Console.ReadLine();
            Console.WriteLine("\n Moi nhap dia chi : "); _Address = Console.ReadLine();
            Console.WriteLine("\n moi nhap so dien thoai : "); _PhoneNumber = Console.ReadLine();
        }

        public int CheckNumber(string myNumber)
        {
            if ((Convert.ToInt32(myNumber) < 4000000) || (Convert.ToInt32(myNumber) > 4999999))
            {
                Console.WriteLine("\n So dien thoai " + myNumber + " khong dung cho phep \n");
                return 1;
            }

            XmlDocument myDoc = new XmlDocument();
            myDoc.Load("telephone.xml");
            XmlNodeList nodeList = myDoc.GetElementsByTagName("PhoneNumber");

            foreach (XmlNode node in nodeList)
            {
                string title = node.ChildNodes[0].Value;

                if (title.Equals(myNumber))
                {
                    Console.WriteLine("\n So dien thoai " + title + " da ton tai \n");
                    return 1;
                }
            }

            return 0;
        }

        public void add(string myName, string myCode, string myAddress, string myPhoneNumber)
        {
            int i;
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load("telephone.xml");
            i = CheckNumber(myPhoneNumber);
            if (i == 1)
            {
                return;
            }
            XmlElement phone = myDoc.CreateElement("Phone");
            XmlElement phoneName = myDoc.CreateElement("Name");
            XmlElement phoneCode = myDoc.CreateElement("Code");
            XmlElement phoneAddress = myDoc.CreateElement("Address");
            XmlElement PhoneNumber = myDoc.CreateElement("PhoneNumber");

            phoneName.InnerText = myName;
            phoneCode.InnerText = myCode;
            phoneAddress.InnerText = myAddress;
            PhoneNumber.InnerText = myPhoneNumber;

            phone.AppendChild(phoneName);
            phone.AppendChild(phoneCode);
            phone.AppendChild(phoneAddress);
            phone.AppendChild(PhoneNumber);
            myDoc.DocumentElement.AppendChild(phone);

            myDoc.Save("telephone.xml");
            Console.WriteLine("\nThem thanh cong \n\n");
        }

    }
}
